<template>
  <div class="stations-table">
    <div class="table-header">
      <h3 class="table-title">{{ title || '表格数据' }}</h3>
      <span class="total-count">共 {{ tableData.length }} 条数据</span>
    </div>

    <!-- 外层容器：控制整体尺寸和滚动区域 -->
    <div class="table-wrapper">
      <!-- 表头容器：固定定位，不随滚动条移动 -->
      <div class="table-header-container">
        <div class="table-row header-row">
          <div 
            v-for="(col, index) in columns" 
            :key="col.prop" 
            class="table-cell header-cell"
            :style="getColumnStyle(index)"
          >
            {{ col.label }}
          </div>
        </div>
      </div>

      <!-- 表体滚动区域：仅表体滚动，表头固定 -->
      <el-scrollbar class="table-body-scroll" wrap-class="scrollbar-wrap">
        <div class="table-body-container">
          <!-- 空数据状态 -->
          <div v-if="tableData.length === 0" class="empty-row">
            <div class="empty-cell" :style="{ width: `calc(100% - 20px)` }">
              暂无数据
            </div>
          </div>

          <!-- 表体数据行 -->
          <div 
            v-else
            v-for="(row, rowIdx) in tableData" 
            :key="row.id || rowIdx"
            class="table-row body-row"
          >
            <div 
              v-for="(col, colIdx) in columns" 
              :key="col.prop" 
              class="table-cell body-cell"
              :style="getColumnStyle(colIdx)"
            >
              <template v-if="slots[col.prop]">
                <slot :name="col.prop" :row="row" :index="rowIdx" />
              </template>
              <template v-else-if="col.render">
                <span class="content-text">{{ col.render(row) }}</span>
              </template>
              <template v-else>
                <span class="content-text">{{ row[col.prop] || col.default || '-' }}</span>
              </template>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
// 脚本部分完全不变（复用原有逻辑）
import { ref, watch, onMounted, useSlots } from 'vue';
import { ElScrollbar } from 'element-plus';

const slots = useSlots();

const props = defineProps({
  title: { type: String, default: '' },
  columns: { 
    type: Array, 
    required: true,
    validator: cols => cols.every(col => col.prop && col.label)
  },
  data: { type: Array, default: () => [] },
  testData: { type: Array, default: () => [] }
});

const tableData = ref([]);
const measureEl = ref(null);
const containerWidth = ref(0);
const adaptiveWidths = ref([]);

onMounted(() => {
  const el = document.createElement('span');
  Object.assign(el.style, {
    visibility: 'hidden',
    position: 'absolute',
    whiteSpace: 'nowrap',
    padding: '8px 10px',
    fontSize: '12px',
    fontFamily: 'Arial, sans-serif',
    top: '-1000px'
  });
  document.body.appendChild(el);
  measureEl.value = el;

  const container = document.querySelector('.table-body-container');
  if (container) {
    containerWidth.value = container.offsetWidth;
    const observer = new ResizeObserver(entries => {
      containerWidth.value = entries[0].contentRect.width;
    });
    observer.observe(container);
  }

  updateData();
});

const updateData = () => {
  if (props.data.length > 0) {
    tableData.value = [...props.data];
  } else if (props.testData.length > 0) {
    tableData.value = [...props.testData];
  } else {
    tableData.value = [];
  }
  calculateAdaptiveWidths();
};

const getTextWidth = (text) => {
  if (!measureEl.value) return 100;
  measureEl.value.textContent = String(text || '');
  return measureEl.value.offsetWidth;
};

const calculateAdaptiveWidths = () => {
  const widths = [];
  props.columns.forEach((col, index) => {
    if (col.width === undefined || !isValidWidth(col.width)) {
      let maxWidth = getTextWidth(col.label);
      tableData.value.forEach(row => {
        const content = col.render 
          ? (col.render(row) || '') 
          : (row[col.prop] || col.default || '');
        maxWidth = Math.max(maxWidth, getTextWidth(content));
      });
      if (col.prop && slots[col.prop]) {
        maxWidth = Math.max(maxWidth, 200);
      }
      widths[index] = maxWidth;
    } else {
      widths[index] = 0;
    }
  });
  adaptiveWidths.value = widths;
};

const isValidWidth = (width) => {
  if (typeof width === 'number') return true;
  if (typeof width === 'string') {
    return /^\d+px$/.test(width) || /^\d+%$/.test(width);
  }
  return false;
};

const getColumnStyle = (index) => {
  const col = props.columns[index];
  if (!col) return { width: '100px' };

  if (typeof col.width === 'string' && col.width.endsWith('%')) {
    return { width: col.width, minWidth: col.width };
  }

  if (col.width !== undefined && isValidWidth(col.width)) {
    const widthVal = typeof col.width === 'number' 
      ? `${col.width}px` 
      : col.width;
    return { width: widthVal, minWidth: widthVal };
  }

  return { 
    width: `${adaptiveWidths.value[index] || 100}px`,
    minWidth: `${adaptiveWidths.value[index] || 100}px`
  };
};

watch(() => props.data, updateData, { deep: true });
watch(() => props.testData, () => {
  if (props.data.length === 0) {
    updateData();
  }
}, { deep: true });
watch(() => props.columns, calculateAdaptiveWidths, { deep: true, immediate: true });
watch(containerWidth, calculateAdaptiveWidths);

onUnmounted(() => {
  if (measureEl.value) {
    document.body.removeChild(measureEl.value);
  }
});
</script>

<style scoped>
.stations-table {
  background: linear-gradient(145deg, #0c2a5f, #082252);
  border: 1px solid rgba(95, 158, 255, 0.3);
  border-radius: 6px;
  padding: 0 10px 10px;
  box-sizing: border-box;
  min-height: 300px;
  font-family: 'Arial, sans-serif';
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid rgba(95, 158, 255, 0.2);
  margin-bottom: 10px;
}

.table-title {
  font-size: 16px;
  color: #8ec5fc;
  margin: 0;
}

.total-count {
  font-size: 12px;
  color: #8ec5fc;
  padding: 3px 8px;
  background: rgba(15, 45, 100, 0.3);
  border-radius: 4px;
}

/* 核心修改：表格外层容器 */
.table-wrapper {
  position: relative; /* 作为表头的定位基准 */
  height: calc(100% - 60px); /* 预留标题栏高度 */
  min-height: 240px; /* 最小高度确保显示正常 */
}

/* 表头容器：固定在顶部，不随滚动移动 */
.table-header-container {
  position: sticky;
  top: 0;
  z-index: 2; /* 确保表头在表体上方 */
  background: inherit; /* 继承父容器背景，避免透明穿透 */
}

/* 表体滚动区域 */
.table-body-scroll {
  max-height: calc(100% - 38px); /* 减去表头高度，避免遮挡 */
  overflow: auto;
}

.scrollbar-wrap {
  overflow-x: auto !important;
  overflow-y: auto !important;
}

/* 表体容器：与表头保持相同的列宽基准 */
.table-body-container {
  width: 100%;
  min-width: 800px;
}

/* 表格行和单元格样式（保持原有） */
.table-row {
  display: flex;
  width: 100%;
}

.table-cell {
  padding: 8px 10px;
  box-sizing: border-box;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header-cell {
  font-size: 12px;
  color: #8ec5fc;
  font-weight: 600;
  background: rgba(10, 36, 85, 0.9);
  border-bottom: 1px solid rgba(95, 158, 255, 0.3);
}

.body-cell {
  font-size: 12px;
  color: #e0f0ff;
  border-bottom: 1px solid rgba(95, 158, 255, 0.15);
}

.body-row:hover {
  background: rgba(100, 149, 237, 0.05);
}

.empty-row {
  padding: 20px 0;
}

.empty-cell {
  font-size: 12px;
  color: #8ec5fc;
  text-align: center;
  padding: 20px;
  background: rgba(10, 36, 85, 0.3);
  margin: 0 auto;
}

/* 滚动条样式（保持美化） */
:deep(.el-scrollbar__bar) {
  background-color: rgba(150, 150, 150, 0.2) !important;
}

:deep(.el-scrollbar__thumb) {
  background-color: rgba(100, 149, 237, 0.5) !important;
  border-radius: 4px !important;
}

:deep(.el-scrollbar__thumb:hover) {
  background-color: rgba(100, 149, 237, 0.8) !important;
}
</style>